package com.yhgm.utils;

import com.yhgm.constant.Constant;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author xinmiao
 * @description
 * @date 2023/4/18 19:57
 */
@Component
public class MyZipUtil {
    public void getZip(Long userId,HttpServletResponse response) throws IOException {
        OutputStream out = response.getOutputStream();
        try {
            response.setCharacterEncoding("UTF-8");
            String path = Constant.proBiologyImagePath+"package/package"+userId+".zip";
            File file = new File(path);
            byte[] data = getStream(path);
            // 压缩包名称
            String downloadName = file.getName();
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(downloadName, "utf-8").replaceAll("\\+", "%20"));
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream;charset=UTF-8");
            if (data != null) {
                out.write(data);
            }
            if(!file.delete()){
                file.deleteOnExit();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }finally {
            try{
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private byte[] getStream(String filePath) {
        byte[] buffer = null;
        File file = new File(filePath);
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fis!=null) {
                    fis.close();
                }
                if(bos!=null) {
                    bos.close();
                }
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer;
    }
}
